package myjava.b_array;

import java.util.Arrays;

/**
 * @Auther: cty
 * @Date: 2019/10/30
 * @Description: 二分法查找
 * @version: 1.0
 */
public class E_TestBinarySearch {
    public static void main(String[] args) {
        int[] arr = {30,20,50,10,80,9,7,12,100,40,8};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        int value = 40;  //要查找的值
        System.out.println(myBinarySearch(arr,value));
    }

    public static int myBinarySearch(int[] arr,int value) {
        int low = 0;
        int high = arr.length-1;

        while(low<=high){
            int mid = (low+high)/2;

            if(value==arr[mid]){
                return mid;
            }
            if(value>arr[mid]){
                low = mid+1;
            }
            if(value<arr[mid]){
                high = mid-1;
            }
        }
        return -1;
    }

}
